import { createRouter, createWebHashHistory } from 'vue-router';
import { getRoutes } from '@/api/layout/index.js'

const routes = [
    {
        path: '/',
        name: 'login',
        meta: {
            title: '登录',
            roles: ['admin', 'editor']
        },
        component: () => import('../views/Login/index.vue')
    },
    {
        path: '/layout',
        name: 'Layout',
        component: () => import('../views/layout/index.vue'),
        children: [
            {
                path: '/home',
                name: 'Home',
                meta: {
                    title: '首页',
                    roles: ['admin', 'editor']
                },
                component: () => import('../views/home/index.vue')
            },
            {
                path: '/user',
                name: 'User',
                meta: {
                    title: '用户主页',
                    roles: ['admin', 'editor']
                },
                component: () => import('../views/user/index.vue')
            },
            {
                path: '/power',
                name: 'Power',
                meta: {
                    title: '权限管理',
                    roles: ['admin']
                },
                component: () => import('../views/power/index.vue')
            },
            {
                path: '/purchasing',
                name: 'Purchasing',
                meta: {
                    title: '采购订单',
                    roles: ['admin', 'editor']
                },
                component: () => import('../views/purchasing/index.vue')
            },
            {
                path: '/warehouse',
                name: 'Warehouse',
                meta: {
                    title: '仓库管理',
                    roles: ['admin']
                },
                component: () => import('../views/storage/warehouse/index.vue')
            },
            {
                path: '/viper',
                name: 'viper',
                meta: {
                    title: 'vip管理',
                    roles: ['admin']
                },
                component: () => import('../views/people/viper/index.vue')
            },
            {
                path: '/403',
                name: '403',
                meta: {
                    title: '无权限',
                    roles: ['admin', 'editor']
                },
                component: () => import('../views/403.vue')
            }
        ]
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const role = JSON.parse(window.sessionStorage.getItem('userInfo')) // 对象字符串转数组
    if(to.path === '/') {
        return next()
    }
    if (!to.meta.roles.includes(role.job)) {
        return next('/403')
    }
    const userInfo = window.sessionStorage.getItem('userInfo')
    if (!userInfo) {
        return next('/')
    }
    next()
})

export default router
